package zhtt;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.BeforeClass;
import org.junit.Test;
import zhtt.demo01.Blog;
import zhtt.demo01.BlogMapper;

import java.io.Reader;

/**
 * Created by zhtt on 2017/4/29.
 */
public class JdbcTransaction {

    private static SqlSessionFactory sqlSessionFactory;
    private static Reader reader;

    @BeforeClass
    public static void setUpBeforeClass() throws Exception {
        try {
            reader = Resources.getResourceAsReader("Configuration.xml");
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
            sqlSessionFactory.getConfiguration().addMapper(BlogMapper.class);
        } finally {
            if (reader != null) {
                reader.close();
            }
        }
    }

    @Test
    public void updateTxTest() {
        SqlSession session = sqlSessionFactory.openSession(false); // 打开会话，事务开始
        try {
            BlogMapper mapper = session.getMapper(BlogMapper.class);
            Blog blog = new Blog(1,"transaction", "Test transaction");
            int affectedCount = mapper.update(blog); // 因后面的异常而未执行commit语句
            Blog blog2 = new Blog(1,"transaction", "Test transaction");
            int affectedCount2 = mapper.update(blog2); // 因后面的异常而未执行commit语句
            int i = 2 / 0; // 触发运行时异常
            session.commit(); // 提交会话，即事务提交
        } finally {
            session.close(); // 关闭会话，释放资源
        }
    }

    @Test
    public void save(){
        SqlSession session = sqlSessionFactory.openSession(false);
        try{
            BlogMapper mapper = session.getMapper(BlogMapper.class);
            Blog blog = new Blog(1,"transaction", "Test transaction");
            int id=mapper.save(blog);
            System.out.println(id);
            session.commit();
        }finally {
            session.close();
        }
    }

    @Test
    public void update() {
        SqlSession session = sqlSessionFactory.openSession(false); // 打开会话，事务开始
        try {
            BlogMapper mapper = session.getMapper(BlogMapper.class);
            Blog blog = new Blog(1,"transac23423tion", "Test tran234saction");
            System.out.println(blog);
            session.commit(); // 提交会话，即事务提交
        } finally {
            session.close(); // 关闭会话，释放资源
        }
    }

}
